import requests
import json
import time
import os
import sys
import subprocess
from datetime import datetime

# 全局配置变量
config = None

def load_config():
    global config
    # 获取用户目录
    user_dir = os.path.expanduser('~')
    user_config_path = os.path.join(user_dir, '.mail_client_config.json')
    
    # 首先尝试从用户目录读取配置文件
    if os.path.exists(user_config_path):
        with open(user_config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        return config
    else:
        print("错误: 配置文件未找到")
        sys.exit(1)

def get_inbox(unread_only=False):
    global config
    url = f"{config['server_url']}/inbox/{config['user']}"
    params = {'unread_only': str(unread_only).lower()}
    try:
        response = requests.get(url, params=params)
        return response.json()
    except Exception as e:
        return {'status': 'error', 'message': str(e)}
        
def show_unread_mails():
    result = get_inbox(unread_only=True)
    if result['status'] == 'success':
        mails = result['mails']
        if mails:
           os.system(' start cmd.exe /K mymail --show-mail ' + mails[0]['id'])
           time.sleep(5)
    else:
        time.sleep(20)

# 初始化配置
load_config()

while True:
    try:
        show_unread_mails()
        time.sleep(config['check_interval'])
    except:
        exit()